#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <semaphore.h>
#include <errno.h>
#define MAX 100

static sem_t sem; //互斥量
static int global=1;

void *t1_exe(void *arg) {
    while (global<MAX) {
        sem_wait(&sem);
        global++;
        printf("In thread1 before increment global=%d\n",global);
        sem_post(&sem);
        sleep(5);
    }
}

void *t2_exe(void *arg) {
    while (global<MAX) {
        sem_wait(&sem);
        printf("In thread2 before double global=%d\n",global);
        global*=2;
        printf("In thread2 after double global=%d\n",global);
        sem_post(&sem);
        sleep(6);
    }
}

void main() {
    pthread_t pid1,pid2;
    int error1,error2;
    if ( sem_init (&sem,0 , 1)==-1 ) {
        perror("sem initialized failed");
        exit(0);
    }
    error1=pthread_create(&pid1,NULL, t1_exe,NULL);
    error2=pthread_create(&pid2,NULL, t2_exe,NULL);
    if (error1!=0||error2!=0) {
        printf("pthread_create failed ");
        return ;
    }
    pthread_join(pid1,NULL);
    pthread_join(pid2,NULL);
    sem_destroy(&sem);
    return ;
}

